% Determine the width of the narrow bar.
% ======================================
% The algorithm tries to fit the data with a sin() function, local
% maximum is then considered the ideal width of the narrow bar:
%
%	y ~ A + C*sin(x+B)
%
% so the amplitude of the sine wave is adjustable. Then
%
% y ~ A + C*sin(B)*cos(x) + C*cos(B)*sin(x)
%
% which can be seen as generic linear model (regression):
%
% y ~ b0 + b1*x1 + b2*x2 , where x1=cos(x) and x2=sin(x)
%
% where the 'design matrix' comes from the GLM theory
% (http://en.wikipedia.org/wiki/Design_matrix)
%
%  yi = b0 + b1*wi + b2*xi     i(1,n)
%
%  |y1|   |1 w1 x1|
%  |y2|   |1 w2 x2| |b0|
%  |y3| = |1 w3 x3| |b1|
%  |..|   |.......| |b2|
%  |yn|   |1 wn xn|
%
% After calculating the vector |b| the original A,B,C are:
% A = b0
% b1/b2 = tan(B)  ====>  B = atan(b1/b2)
% b1^2 + b2^2 = C^2*(sin^2(B) + cos^2(B)) = C^2  ====> C = sqrt(b1^2 + b2^2)
%
function yc = regsin0(fin)
	lfin=fin(1,1:(columns(fin)/2));
	y=lfin';   
	x=[1:rows(y)]';
	x1=cos(x);
	x2=sin(x);
	X(:,1)=ones(1,rows(x));
	X(:,2)=x1;
	X(:,3)=x2;
	a=inv(X'*X)*(X'*y);
	A=a(1,1);
	B=atan(a(2,1)/a(3,1));
	C=sqrt(a(2,1)^2 + a(3,1)^2);
	for i=1:rows(y)
		yc(i,1)=A+C*sin(i+B);
	endfor
end

